package com.ruisoft.business.stock.service;

import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ruisoft.base.dao.BaseDao;
import com.ruisoft.base.service.BaseService;
import com.ruisoft.business.stock.bean.StockMove;
import com.ruisoft.business.stock.bean.StockPicking;
import com.ruisoft.business.stock.bean.StockQuant;
import com.ruisoft.common.CommonUtil;
import com.ruisoft.core.param.CacheDataFactory;

/**
 * Created with IntelliJ IDEA.
 * User: LFC
 * Date: 2015/8/11
 * Time: 21:37
 * To change this template use File | Settings | File Templates.
 */

@Service
public class StockService extends BaseService {

    @Autowired
    public BaseDao baseDao;

    @Autowired
    private CacheDataFactory cacheData;


    /**
     * 按照bean形式查询库存信息
     * @param info
     * @return
     * @throws Exception
     */
    public JSONObject searchStock(Object[] info) throws Exception {
    	
        System.out.println("获取分拣单类型数据");
        JSONObject pickTypeJson=   cacheData.getJsonDataById("STOCK_PICKING_TYPE","1");
        String srcLocation=(String) pickTypeJson.get("location_src_id");
        String destLocation=(String) pickTypeJson.get("location_dest_id");
        System.out.println("源库位"+srcLocation);
        System.out.println("目的库位"+destLocation);
        
        List<StockPicking> stockPickings = baseDao.queryList(StockPicking.class, info, "stock.select.stock_picking");
        List<StockMove> stockMoves = baseDao.queryList(StockMove.class, info, "stock.select.stock_picking_move");
        StockPicking stockPicking = stockPickings.get(0);
        
        System.out.println("第一次获取数据");
        stockPicking.setPicking_type_name(cacheData.getNameById("STOCK_PICKING_TYPE",stockPicking.getPicking_type_id()));
        System.out.println("第二次获取数据");
        stockPicking.setPicking_type_name(cacheData.getNameById("STOCK_PICKING_TYPE",stockPicking.getPicking_type_id()));
        stockPicking.setItems(stockMoves);
        JSONObject result = new JSONObject(net.sf.json.JSONObject.fromObject(stockPicking));
        return result;
    }

    /**
     * 按照json格式查询库存信息
     * @param id
     * @return
     * @throws Exception
     */
    public JSONObject searchStock(String id) throws Exception {
        List<JSONObject> stockPick =  baseDao.queryId(id,"stock.select.stock_picking");
        List<JSONObject> stockMove =  baseDao.queryId(id,"stock.select.stock_picking_move");
        JSONObject result = stockPick.get(0);
        result.put("items", new JSONArray(stockMove).toString());
        return result;
    }
    /**
     * 保存库存分拣单
     * @param jsonData
     * @return
     * @throws Exception
     */
    public JSONObject saveStock(JSONObject jsonData) throws Exception {
    	// 分拣单ID 赋值  ，PKUUID
        String picking_id = CommonUtil.getPKUUID();
    	//主键赋值
        jsonData.put("id",picking_id);
        //获取规则编号
        jsonData.put("code",getKeyByRule("stock.picking.code"));
        //保存库存分拣单
        baseDao.add(jsonData,"stock.add.stock_picking");
        
        //库存移动明细 stock_move 明细
        JSONArray itemData = jsonData.getJSONArray("items");
        JSONObject[] item = new JSONObject[itemData.length()];
        for (int i = 0; i < itemData.length(); i++) {
            item[i] = itemData.getJSONObject(i);
            item[i].put("picking_id", picking_id);
            item[i].put("id", CommonUtil.getPKUUID());
            
            //保存库存移动明细 stock_move
            baseDao.add(item[i],"stock.add.stock_move");
        }
        
        // 保存成功后返回界面数据
        jsonData.put("items",item);
        
        return jsonData;
    }

    /**
     * 修改库存管理
     * @param jsonData
     * @return
     * @throws Exception
     */
    public JSONObject updateStock(JSONObject jsonData) throws Exception {
    	//更新库存分拣单数据处理
    	
    	//1、每次修改都应更新 修改人（write_uid），修改时间（write_date）
    	jsonData.put("write_uid","getSession.uid");
    	jsonData.put("write_date",CommonUtil.getCurDateTime());
    	
    	//2、根据主键更新
        baseDao.update(jsonData, "stock.update.stock_picking");
        
        //更新库存移动明细 move
        
        JSONArray itemData = jsonData.getJSONArray("items");
        JSONObject[] item = new JSONObject[itemData.length()];
        
        //明细数据处理状态 __status
        // 
        String __status = "";
        for (int i = 0; i < itemData.length(); i++) {
            item[i] = itemData.getJSONObject(i);
            
            __status =(String)item[i].get("__status");
            if("update".equals(__status)) {
                baseDao.update(item[i], "stock.update.stock_move");
            }
            if("add".equals(__status)) {
                baseDao.add(item[i], "stock.update.stock_move");
            }
        }
        return jsonData;
    }

    /**
     * 更新库存状态，保存实际库存
     * @param jsonData
     * @return
     * @throws Exception
     */
    public JSONObject updateQuant(JSONObject jsonData) throws Exception {
        baseDao.update(jsonData, "stock.update.stock_picking_state");
        JSONArray itemData = jsonData.getJSONArray("items");
        JSONObject[] item = new JSONObject[itemData.length()];
        for (int i = 0; i < itemData.length(); i++) {
            item[i] = itemData.getJSONObject(i);
            baseDao.update(item[i], "stock.update.stock_move_state");
            //保存实际库存
            saveQuant(item[i]);
        }
        return jsonData;
    }

    /**
     * 收货处理
     * @param jsonData 库存移动数据
     * @return
     * @throws Exception
     */
    public int saveQuant(JSONObject jsonData) throws Exception {
       int result = 0;
//       Map<String, Class> classMap = new HashMap<String, Class>();
//       classMap.put("items", StockMove.class);
//       StockPicking stockPicking = (StockPicking) net.sf.json.JSONObject.toBean(
//                net.sf.json.JSONObject.fromObject(jsonData.toString()), StockPicking.class,classMap);
//       StockMove stockMove = (StockMove) stockPicking.getItems().get(0);
       
       //1、更新库存分拣单专状态为 已收货 完成 done
       jsonData.put("state", "done");
   		//1、每次修改都应更新 修改人（write_uid），修改时间（write_date）
   		jsonData.put("write_uid","getSession.uid");
   		jsonData.put("write_date",CommonUtil.getCurDateTime());
       
       baseDao.update(jsonData, "stock.update.stock_picking_state");
       
       //2、根据 picking_id 批量更新 stock_move 状态 state=done
       JSONObject moveJsonData= new JSONObject();
       moveJsonData.put("picking_id", jsonData.get("id"));
       moveJsonData.put("state", "done");
   		//每次修改都应更新 修改人（write_uid），修改时间（write_date）
       moveJsonData.put("write_uid","getSession.uid");
       moveJsonData.put("write_date",CommonUtil.getCurDateTime());
       
       baseDao.update(moveJsonData, "stock.update.stock_move_state_bypickid");
       
       /*
        * 由库存数据生成库存帐数据，并进行库存帐数据保存处理
        */
       //itemData 为库存移动明细数据，逐条处理
       StockMove stockMove = new StockMove();
       StockQuant quant = new StockQuant();
       
       JSONArray itemData = jsonData.getJSONArray("items");
       JSONObject[] item = new JSONObject[itemData.length()];
       for (int i = 0; i < itemData.length(); i++) {
           item[i] = itemData.getJSONObject(i);
           //通过json转业务bean方式处理
           StockMove stockMoveBean =(StockMove) net.sf.json.JSONObject.toBean(
                   net.sf.json.JSONObject.fromObject(item[i].toString()),StockMove.class);
       
        //对象赋值，新对象其他方法完成处理
        BeanUtils.copyProperties(stockMove, stockMoveBean);
        
        //两个业务对象相同名称属性赋值
        BeanUtils.copyProperties(quant, stockMove);
        //获取ID
        String id = CommonUtil.getPKUUID();
        String id2 = CommonUtil.getPKUUID();

        StockQuant quant2 = new StockQuant();
        //主键ID
        quant.setId(id);
        quant.setQuant_id(id);
        quant.setMove_id(stockMove.getId());
//        //公司
//        quant.setCompany_id(stockMove.getCompany_id());
//        //业务部门
//        quant.setDept_id(stockMove.getDept_id());
//        //仓房
//        quant.setWarehouse_id(stockMove.getWarehouse_id());
//        //库位
//        quant.setLocation_id(stockMove.getLocation_id());
//        //产品ID
//        quant.setProduct_id(stockMove.getProduct_id());
        //数量
        quant.setQty(stockMove.getProduct_uom_qty());
        //成本
        quant.setCost(stockMove.getCost());
        //批次ID
        quant.setLot_id(stockMove.getRestrict_lot_id());
        //生成日期
        quant.setIn_date(CommonUtil.getCurDateTime());
        //制单人
        quant.setCreate_uid("create_uid");
        //制单日期
        quant.setCreate_date("create_date");
        //修改人
        quant.setWrite_uid("write_uid");
        //修改日期
        quant.setWrite_date("write_date");
        //预留占用移动单ID
        quant.setReservation_move_id("reservation_move_id");
        //负向移动单ID
        quant.setNegative_move_id("negative_move_id");

        /*
         * bean 对象转换赋值等业务逻辑处理完成后，转为json对象，进行数据库保存处理
         */
        JSONObject jsonQuant = new JSONObject(net.sf.json.JSONObject.fromObject(quant));
        
        //增加实际库存
        baseDao.add(jsonQuant, "stock.add.stock_quant");
        //建立实际库存与库存移动关系
        baseDao.add(jsonQuant, "stock.add.stock_quant_move_rel");
        
       }
       
        return result;
    }
}
